#include "soundplayer.h"
#include <phonon/backendcapabilities.h>


// Constructor, called from the singleton constructor
SoundPlayer::SoundPlayer(){

    this->mMediaObject = new Phonon::MediaObject(this);
    this->mAudioOutput = new Phonon::AudioOutput(this);

	this->mMediaObject->setTickInterval(20); // set the tick interval to 20ms
	
    // Connect MediaObject to Output
    Phonon::Path path = Phonon::createPath(this->mMediaObject, this->mAudioOutput);
	
}

// initialize the static variables
SoundPlayer* SoundPlayer::instance = 0;

SoundPlayer* SoundPlayer::getInstance()
{
	if(instance == 0)
	{
		instance = new SoundPlayer();
	}
	return instance;
}

void SoundPlayer::destroyInstance()
{
	delete instance->mMediaObject;
    delete instance->mAudioOutput;
}

SoundPlayer::~SoundPlayer(){}

void SoundPlayer::setPosition(qint64 position)
{
	SoundPlayer::mPosition = position;
}

void SoundPlayer::setAudiofile(QString string)
{
	this->mMediaObject->setCurrentSource(Phonon::MediaSource(string));
	// we need to convert the player into the Playing/Paused state
	// else no seeking in the stream is allowed
	this->mMediaObject->pause();
	
}

void SoundPlayer::play()
{
	this->mMediaObject->play();
}

void SoundPlayer::stop()
{
	this->mMediaObject->stop();
}

// function that triggers the play stop event when the space key is hit
// according to the playing state of the audio player
void SoundPlayer::playStopKey()
{
	int state = SoundPlayer::mMediaObject->state();
	
	if ( (state ==  Phonon::StoppedState) || (state == Phonon::PausedState) )
	{
		SoundPlayer::mMediaObject->play();
	}
	else 
	{
		SoundPlayer::mMediaObject->pause();
	}

}
